const express = require('express')
const goodsRouter = express.Router()

//菜品列表
const goodsList = [
	{ id: 1, name: '回锅肉', price: 18.88, num: 10 },
	{ id: 2, name: '鱼香肉丝', price: 28.75, num: 5 },
]

/**
 * 菜品列表
 */
goodsRouter.get('/goods/list', (req, res) => {
	res.send({
		code: 1,
		list: goodsList,
	})
})

/**
 * 添加商品
 *  get请求参数 query
 */
goodsRouter.get('/goods/add', (req, res) => {
	//接收参数
	const id = req.query.id
	const name = req.query.name
	const price = req.query.price
	const num = req.query.num
	//添加到数组
	goodsList.push({
		id,
		name,
		price,
		num,
	})
	//响应
	res.send({
		code: 1,
		message: '添加商品成功!',
	})
})

/**
 * 删除商品
 * 根据商品ID删除商品
 */
goodsRouter.get('/goods/delete', (req, res) => {
	//接收参数
	const id = req.query.id
	//删除数组元素
	const index = goodsList.findIndex(item => item.id == id)
	goodsList.splice(index, 1)
	//响应
	res.send({
		code: 1,
		message: '删除商品成功!',
	})
})

module.exports = { goodsRouter }
